import Vue from 'vue'
import App from './App.vue'
import store from './store'
import cookie from 'js-cookie'
import router from './router'
import api from './api/index.js'
import { message, Modal, Progress, Tabs } from 'ant-design-vue'

const serverUrl = 'http://49.235.166.90:9527'

Vue.config.productionTip = false
Vue.use(Progress).use(Tabs)

// 首次登陆
if (window.location.search.includes('verify_request')) {
  const query = {}
  window.location.search.replace('?', '').split('&').forEach(qs => {
    const temp = qs.split('=')
    query[temp[0]] = temp[1]
  })

  api.yibanApi.verifyToken(query).then(res => {
    if (res.code === 0) {
      cookie.set('token', res.data.access_token, { expires: 1, path: '' })
      getUser(res.data.access_token)
    }
  }).catch(err => {
    console.log(err)
  })
} else {
  const token = cookie.get('token')
  console.log(token)
  if (token) {
    getUser(cookie.get('token'))
  } else {
    window.location.href = serverUrl + '/login'
  }
}

function getUser (token) {
  api.yibanApi.getUserInfo({ token }).then(res => {
    if (res.status === 'success') {
      store.state.userInfo = res.info
      getConfig('homeConfig')
      getConfig('baseConfig')
      if (window.location.href.includes('verify_request')) {
        router.push('/')
      }
    } else {
      // 请求失败，token无效清除token
      cookie.remove('token')
      window.location.href = serverUrl + '/login'
    }
  })
}

function getConfig (type) {
  api.report.getConfig({ type }).then(res => {
    if (res.code === 0) {
      if (res.data[0]) {
        store.state[type] = res.data[0].data
      }
    } else {
      message.error(res.userMsg)
    }
  })
}

message.config({
  top: '100px'
})

Vue.prototype.$message = message
Vue.prototype.$confirm = Modal.confirm

new Vue({
  store,
  router,
  components: { App },
  render: h => h(App)
}).$mount('#app')
